<template>
  <div class="app-container">

    <el-alert title="学期管理说明：" type="info" style="margin-bottom:20px" show-icon>
      <div style='line-height:28px'>
              （1）设置系统中当前学期；<br/>
              （2）缓缴费录入时，默认为当前设置的学期
      </div>
      </el-alert>

    <!-- 收费区间 -->
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        :icon="Refresh"
        @click="handleFilter"
        >刷新</el-button
      >
      <el-button class="filter-item" type="primary" @click="handlePublish"
        >添加学期</el-button
      >
    </div>

    <!-- 查询结果 -->
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      :height="tableHeight() + 4"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        align="center"
        min-width="250"
        label="学期"
        prop="term"
      />
    

      <el-table-column
        align="center"
        min-width="150"
        label="注册开始日期"
        prop="beginDate"
      >
      <template #default="scope">
        {{ formateDateYMD(scope.row.beginDate) }}
      </template>
      </el-table-column>
      <el-table-column
        align="center"
        min-width="150"
        label="注册结束日期"
        prop="endDate"
      >
      <template #default="scope">
        {{ formateDateYMD(scope.row.endDate) }}
      </template>
      </el-table-column>

      <el-table-column
        align="center"
        min-width="250"
        label="是否为当前学期"
      >
        <template #default="scope">
           <el-tag v-if="scope.row.currentMark == '1' ">当前学期</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column
        align="center"
        min-width="150"
        label="备注"
        prop="remark"
      />

      <el-table-column
        align="center"
        label="操作"
        min-width="250"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleSetCurrent(scope.row)" v-if="scope.row.currentMark== '0' ">设为当期</el-button>
          <el-button type="primary" size="small" @click="handleCancelCurrent(scope.row)" v-if="scope.row.currentMark== '1' ">取消当期</el-button>
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pageHolder">
      <el-pagination
        background
        v-model:page-size="listQuery.limit"
        layout="total,sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="pageChange"
        @size-change="handleSizeChange"
      />
    </div>

    <el-dialog
      :title="formTitle"
      v-model="showAdd"
      :close-on-click-modal="false"
      width="60%"
      @close="handleClose"
      :close-on-press-escape="false"
    >
      <el-form
        style="margin-top:30px"
        ref="formRef"
        :rules="rules"
        :model="theForm"
        label-width="150px"
      >
        <el-form-item label="学期" prop="term">
          <el-input
            v-model="theForm.term"
            maxlength="10"
            style="width: 250px"
            clearable=""
          >
          </el-input>
        </el-form-item>

        <el-form-item label="注册开始日期" prop="beginDate" >
            <el-date-picker
            style="width: 250px"
            format="YYYY年MM月DD日"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="theForm.beginDate"
            type="date"
            :editable="false"
            placeholder="选择日期">
          </el-date-picker>
          <div style="position: absolute;margin-left: 260px;color:#666">
            (仅在设置日期当日以及以后方可注册)
          </div>
        </el-form-item>

        <el-form-item label="注册结束日期" prop="endDate" >
            <el-date-picker
            style="width: 250px"
            format="YYYY年MM月DD日"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="theForm.endDate"
            type="date"
            :editable="false"
            placeholder="选择日期">
          </el-date-picker>
          <div style="position: absolute;margin-left: 260px;color:#666">
            (结束日期之后将不能注册)
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="theForm.remark"
            maxlength="10"
            style="width: 250px"
            clearable=""
          >
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAdd = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)"
            >保 存</el-button
          >
        </div>
      </template>
    </el-dialog>

   
  </div>
</template>

 
<script setup lang="ts">
import { tableHeight } from "@/util/index.ts";
import configs from "@/util/config.ts";
import http from "@/api/js/http";
import {FormInstance} from "element-plus";
import { ref, reactive, onMounted } from "vue";
import msg from "@/util/Message.ts";
import { Refresh } from "@element-plus/icons-vue";
//@ts-ignore
import {formateDateYMD} from '@/util/date.js'

const formRef = ref<FormInstance>();
const showAdd = ref(false);
const theForm = reactive<ITerm>({
  id: null,
  term: null,
  remark: null,
  beginDate:null,
  endDate:null,
  currentMark:'0'
});
const formTitle = ref("");
const list = ref<any>([]);
const total = ref<number>(0);
const listLoading = ref(true);
const listQuery = reactive({
  page: 1,
  durationCode: null,
  limit: configs.limit,
});

const rules = ref({
  term: [{ required: true, message: "不能为空", trigger: "change" }],
  beginDate: [{ required: true, message: "不能为空", trigger: "change" }],
});

onMounted(() => {
  getList();
});


function pageChange(page: number) {
  listQuery.page = page;
  getList();
}
function handlePublish() {
  showAdd.value = true;
  resetForm();
  formTitle.value = "添加学期";
}
function handleUpdate(row:ITerm) {
  showAdd.value = true;
  resetForm();
  formTitle.value = "修改学期";

  theForm.id = row.id;
  theForm.currentMark = row.currentMark;
  theForm.term = row.term;
  theForm.remark = row.remark;
  theForm.beginDate = row.beginDate;
  theForm.endDate = row.endDate;

}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      doSubmit();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const handleSetCurrent = (row:IFeeDuration)=>{
  http.post('/term/setCurrent',row)
  .then((resp)=>{
    if(resp.code == 0){
      msg.success('设置成功');
      getList();
    }else{
      msg.error(resp.msg);
    }
    
  });
}

const handleCancelCurrent = (row:IFeeDuration)=>{
  http.post('/term/cancelCurrent',row)
  .then((resp)=>{    
    if(resp.code == 0){
      msg.success('已取消当期');
      getList();
    }else{
      msg.error(resp.msg);
    }

  });
}

function handleSizeChange() {
  getList();
}


function doSubmit() {
  var url = "/term/create";
  if(theForm.id != null) url = '/term/update';
  var data = theForm;

  http.post(url, data).then(() => {
    showAdd.value = false;
    getList();
    msg.success();
  });
}

function getList() {
  listLoading.value = true;

  http
    .get<IList<IFeeDuration>>("/term/list", listQuery)
    .then((resp) => {
      var respList = resp?.data?.list;
      list.value = respList;
      listLoading.value = false;
      if (resp?.data?.total) {
        total.value = resp?.data?.total;
      }
    })
    .catch(() => {
      list.value = [];
      total.value = 0;
      listLoading.value = false;
    });
}

function handleFilter() {
  listQuery.page = 1;
  getList();
}

function handleDelete(row: any) {
  msg.delConfirm().then(() => {
    doDelete(row);
  });
}

function doDelete(row: any) {
  var data = "id=" + row.id;

  http
    .post("/term/delete", data)
    .then(() => {
      msg.success("删除成功");
      getList();
    })
    .catch(() => {
      msg.error("删除失败");
    });
}

function handleClose() {
  resetForm();
  formRef.value?.clearValidate();
}

function resetForm(){
  theForm.id = null;
  theForm.currentMark = "0";
  theForm.term = null;
  theForm.beginDate = null;
  theForm.remark = null;
}
</script>
